import json
import re

from django.contrib.auth import login, logout

from users.models import User
from utils.response_code import *
from django.http import HttpResponse, JsonResponse
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection


class ImageCodeView(View):
    def get(self, request):
        """获取图片验证码"""

        # 获取数据
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')

        # 校验数据
        if not cur:
            return HttpResponse('参数不全', status=400)

        # 生成图片验证码
        text, image = captcha.generate_captcha()

        redis_client = get_redis_connection('verify')
        if pre:
            redis_client.delete(pre)
        redis_client.setex(cur, 300, text)

        # 返回响应
        return HttpResponse(image, 'image/jpeg')


class SmsCodeView(View):
    def post(self, request):
        """获取短信验证码"""

        # 接收数据
        mobile = json.loads(request.body).get('mobile')
        uuid = json.loads(request.body).get('id')
        text = json.loads(request.body).get('text')

        # 校验数据
        if not re.match('1[35678]\d{9}$', mobile):
            return JsonResponse({
                'errno': RET.MOBILEERR,
                'errmsg': error_map[RET.MOBILEERR]
            })

        # 校验图片验证码
        redis_client = get_redis_connection('verify')
        img_text = redis_client.get(uuid)
        if img_text:
            img_text = img_text.decode()

        if text.upper() != img_text.upper():
            return JsonResponse({
                'errno': RET.IMAGECODEERR,
                'errmsg': error_map[RET.IMAGECODEERR]
            })
        redis_client.delete(uuid)

        # 发送短信验证码
        from random import randint
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)

        # from libs.yuntongxun.sms import CCP
        # ccp = CCP()
        # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)

        # 返回响应

        redis_client.setex('sms_code_{}'.format(mobile), 300, sms_code)
        return JsonResponse({
                'errno': RET.OK,
                'errmsg': error_map[RET.OK]
            })


class RegisterView(View):
    def post(self, request):
        """注册用户"""

        # 获取数据
        mobile = json.loads(request.body).get('mobile')
        phonecode = json.loads(request.body).get('phonecode')
        password = json.loads(request.body).get('password')

        # 校验数据
        if not all([mobile, phonecode, password]):
            return JsonResponse({
                'errno': RET.PARAMERR,
                'errmsg': error_map[RET.PARAMERR]
            })

        if not re.match('1[35678]\d{9}$', mobile):
            return JsonResponse({
                'errno': RET.MOBILEERR,
                'errmsg': error_map[RET.MOBILEERR]
            })

        redis_client = get_redis_connection('verify')
        sms_code = redis_client.get('sms_code_{}'.format(mobile))

        if sms_code:
            sms_code = sms_code.decode()

        if phonecode != sms_code:
            return JsonResponse({
                'errno': RET.SMSCODERR,
                'errmsg': error_map[RET.SMSCODERR]
            })

        # 创建用户
        user = User.objects.create_user(
            mobile=mobile,
            username=mobile,
            password=password
        )
        login(request, user)

        # 返回响应
        return JsonResponse({
            'errno': '0',
            'errmsg': '注册成功'
        })


class LoginView(View):
    def post(self, request):
        """登录"""

        # 接收数据
        mobile = json.loads(request.body).get('mobile')
        password = json.loads(request.body).get('password')

        # 校验数据
        if not all([mobile, password]):
            return JsonResponse({
                'errno': RET.PARAMERR,
                'errmsg': error_map[RET.PARAMERR]
            })

        # 判断用户是否已注册
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return JsonResponse({
                'errno': RET.USERERR,
                'errmsg': error_map[RET.USERERR]
            })

        # 校验密码
        if user.check_password(raw_password=password):
            login(request, user)
            return JsonResponse({
                'errno': 0,
                'errmsg': '登录成功'
            })
        else:
            return JsonResponse({
                'errno': RET.PWDERR,
                'errmsg': error_map[RET.PWDERR]
            })

    def get(self, request):
        """判断用户是否登录"""

        user = request.user

        if user.is_authenticated:
            return JsonResponse({
                'errno': 0,
                'errmsg': '已登录',
                'data': {
                    'name': user.username,
                    'user_id': user.id
                }
            })

        else:
            return JsonResponse({
                'errno': 4101,
                'errmsg': '未登录'
            })

    def delete(self, request):
        """退出登录"""

        logout(request)

        return JsonResponse({
            'errno': 0,
            'errmsg': '已登出'
        })